// API工具类 - 支持相对路径请求
interface ApiResponse<T = any> {
  success: boolean
  message: string
  data?: T
}

interface RequestOptions extends RequestInit {
  showError?: boolean
}

class ApiClient {
  private baseURL: string

  constructor() {
    // 在开发环境使用相对路径，生产环境可以配置实际的后端地址
    this.baseURL = import.meta.env.DEV ? '' : import.meta.env.VITE_API_BASE_URL || ''
  }

  /**
   * 构建完整的URL
   */
  private buildURL(path: string): string {
    // 如果path已经是完整URL，直接返回
    if (path.startsWith('http://') || path.startsWith('https://')) {
      return path
    }
    
    // 确保path以/开头
    const normalizedPath = path.startsWith('/') ? path : `/${path}`
    return `${this.baseURL}${normalizedPath}`
  }

  /**
   * 获取认证token
   */
  private getAuthToken(): string | null {
    return localStorage.getItem('authToken')
  }

  /**
   * 处理响应
   */
  private async handleResponse<T>(response: Response): Promise<ApiResponse<T>> {
    if (!response.ok) {
      // 处理401未授权
      if (response.status === 401) {
        localStorage.removeItem('authToken')
        localStorage.removeItem('userInfo')
        window.location.href = '/auth'
        throw new Error('登录已过期，请重新登录')
      }
      
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    try {
      const data = await response.json()
      return data
    } catch (error) {
      throw new Error('响应数据格式错误')
    }
  }

  /**
   * 通用请求方法
   */
  async request<T = any>(path: string, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const { showError = true, ...fetchOptions } = options
    
    const url = this.buildURL(path)
    const token = this.getAuthToken()
    
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      ...fetchOptions.headers,
    }

    // 如果有token，添加到请求头
    if (token) {
      (headers as any)['Authorization'] = `Bearer ${token}`
    }

    try {
      const response = await fetch(url, {
        ...fetchOptions,
        headers,
      })

      return await this.handleResponse<T>(response)
    } catch (error) {
      if (showError) {
        console.error('API请求失败:', error)
        alert(error instanceof Error ? error.message : '网络请求失败')
      }
      throw error
    }
  }

  /**
   * GET请求
   */
  async get<T = any>(path: string, options?: RequestOptions): Promise<ApiResponse<T>> {
    return this.request<T>(path, { method: 'GET', ...options })
  }

  /**
   * POST请求
   */
  async post<T = any>(path: string, data?: any, options?: RequestOptions): Promise<ApiResponse<T>> {
    return this.request<T>(path, {
      method: 'POST',
      body: data ? JSON.stringify(data) : undefined,
      ...options,
    })
  }

  /**
   * PUT请求
   */
  async put<T = any>(path: string, data?: any, options?: RequestOptions): Promise<ApiResponse<T>> {
    return this.request<T>(path, {
      method: 'PUT',
      body: data ? JSON.stringify(data) : undefined,
      ...options,
    })
  }

  /**
   * DELETE请求
   */
  async delete<T = any>(path: string, options?: RequestOptions): Promise<ApiResponse<T>> {
    return this.request<T>(path, { method: 'DELETE', ...options })
  }

  /**
   * PATCH请求
   */
  async patch<T = any>(path: string, data?: any, options?: RequestOptions): Promise<ApiResponse<T>> {
    return this.request<T>(path, {
      method: 'PATCH',
      body: data ? JSON.stringify(data) : undefined,
      ...options,
    })
  }
}

// 创建API客户端实例
export const api = new ApiClient()

// 导出类型
export type { ApiResponse, RequestOptions } 